package com.wing.sell.controller.admin;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductType;
import com.wing.product.model.entity.ProductUnitInfo;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductTypeService;
import com.wing.product.service.ProductUnitService;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.FinishedOrderForm;
import com.wing.sell.model.response.*;
import com.wing.sell.service.*;
import com.wing.storage.model.entity.ProductInventory;
import com.wing.storage.service.ProductInventoryService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hz
 */
@Validated
@Api(value = "Admin-成品销售控制层", tags = "#/sell/finishedOrder")
@RestController("finishedOrderController")
@RequestMapping("sell/admin/finishedOrder")
@RequiredArgsConstructor
@Slf4j
public class FinishedOrderController {

    private final FinishedOrderService finishedOrderService;
    private final FinishedOrderDetailService finishedOrderDetailService;
    private final ProductDetailService productDetailService;
    private final ProductTypeService productTypeService;
    private final ProductUnitService productUnitService;
    private final CustomersInfoService customersInfoService;
    private final ProductInventoryService productInventoryService;

    @ApiOperation(value = "查询所有成品销售订单表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "desc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<FinishedOrderVo> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
            , String selCode
            , String customerType
            , String selType
            , String startTime
            , String endTime
            , String selStatus
    ) {

        Page<FinishedOrderVo> pg = new Page<>(page, limit);

        //查询条件
        Map<String,Object> params = new HashMap();
        params.put("sort", StrUtil.toUnderlineCase(sort));
        params.put("order", StrUtil.toUnderlineCase(order));
        params.put("selCode", selCode);
        params.put("customerType", customerType);
        params.put("selType", selType);
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        if (StrUtil.isNotBlank(selStatus)) {
            String[] split = selStatus.split(",");
            params.put("selStatus", split);
        }
        Page<FinishedOrderVo> list = finishedOrderService.pageList4app(pg, params);
        list.getRecords().forEach(info -> {
                    info.setSelStatusName(ProductEnum.finishendOrderStatusEmum.getNameByCode(info.getSelStatus()));
                    if ("2".endsWith(info.getCustomerType())) {
                        CustomersInfo byId = customersInfoService.getById(info.getCustomerId());
                        if (ObjectUtil.isNotEmpty(byId)){
                            info.setCustomerName(byId.getCustomerName());
                        }
                    }
                    info.setPcStatusName(MaintenanceEnum.pcStatusEmum.getNameByCode(info.getPcStatus()));
                }
        );
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @GetMapping("/detail/{id}")
    public JsonResult getDetailById(@PathVariable("id") Long id) {
        FinishedOrderVo finishedOrderVo = finishedOrderService.getDetailBy(id);
        finishedOrderVo.setSelStatusName(ProductEnum.finishendOrderStatusEmum.getNameByCode(finishedOrderVo.getSelStatus()));
        //查询详情
        LambdaQueryWrapper<FinishedOrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FinishedOrderDetail::getFinishedId, id);
        wrapper.eq(FinishedOrderDetail::getIsDeleted, false);

        Map<Long, String> stringMap = productTypeService.list().stream().collect(Collectors.toMap(ProductType::getId, ProductType::getName));
        Map<Long, String> map = productUnitService.list().stream().collect(Collectors.toMap(ProductUnitInfo::getId, ProductUnitInfo::getName));
        List<FinishedOrderDetail> list = finishedOrderDetailService.list(wrapper);

        List<Long> collect = list.stream().filter(info ->
                        ObjectUtil.isNotNull(info.getProductDetailId()))
                .map(FinishedOrderDetail::getProductDetailId)
                .collect(Collectors.toList());

        Map<String,Object> aMap = new HashMap<>(16);
        aMap.put("ids", collect);
        List<ProductDetail> details = productDetailService.list4app(aMap);

        list.forEach(info -> {
            details.forEach(w -> {
                if (info.getProductDetailId() != null && info.getProductDetailId().equals(w.getId())) {
                    info.setSkuCode(w.getSkuCode());
                    info.setSkuSpec(w.getSkuSpec());
                    info.setSkuName(w.getSkuName());
                    info.setSuggestLowestPrice(w.getSuggestionMinPrice());
                    info.setMinPrice(w.getMinPrice());
                    String typeName = w.getProductTypeId() == null ? null : stringMap.get(w.getProductTypeId());
                    info.setProductTypeName(typeName);
                    info.setMainUnitName(w.getMainUnitId() == null ? null : map.get(w.getMainUnitId()));
                    info.setFileUrl(w.getProductPic());
                    QueryWrapper<ProductInventory> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("product_detail_id",w.getId());
                    ProductInventory one = productInventoryService.getOne(queryWrapper);
                    if (ObjectUtil.isNotEmpty(one)){
                        info.setHaveQuantity(one.getQuantity());
                    }
                }
            });
        });
        finishedOrderVo.setDetails(list);
        return JsonResult.success(finishedOrderVo);
    }


    @ApiOperation(value = "添加成品销售订单信息", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody FinishedOrderForm finishedOrderForm) {
        if (finishedOrderService.addInfo(finishedOrderForm)) {
            return JsonResult.success("添加成功");
        } else {
            return JsonResult.fail("添加失败");
        }

    }


    @ApiOperation(value = "修改成品销售订单信息", notes = "修改")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/update")
    public JsonResult update(@RequestBody FinishedOrderForm finishedOrderForm) {
        if (finishedOrderService.updateInfo(finishedOrderForm)) {
            return JsonResult.success("修改成功");
        } else {
            return JsonResult.fail("修改失败");
        }

    }

    @ApiOperation(value = "确认提交", notes = "提交")
    @PostMapping("/submit/{id}")
    public JsonResult submit(@PathVariable("id") Long id) {
        if (finishedOrderService.submit(id)) {
            return JsonResult.success("提交成功");
        } else {
            return JsonResult.fail("提交失败");
        }
    }

    @ApiOperation(value = "审核", notes = "审核")
    @PostMapping("/audit/{id}")
    public JsonResult audit(@PathVariable("id") Long id) {
        if (finishedOrderService.audit(id)) {
            return JsonResult.success("提交成功");
        } else {
            return JsonResult.fail("提交失败");
        }
    }


    @ApiOperation(value = "删除销售订单表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "销售订单表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/delete/{id}")
    public JsonResult delete(@PathVariable("id") Long id) {
        if (finishedOrderService.removeById(id)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询订单中物料信息", notes = "查询-订单sku")
    @GetMapping("/getSkuInfo/{orderId}/{warehouseId}")
    public JsonResult<List<OrderSkuDetailSearchVo>> getSkuInfo(@PathVariable("orderId")Long orderId, @PathVariable("warehouseId")Long warehouseId) {
        List<OrderSkuDetailSearchVo> list = finishedOrderDetailService.listByInfo(orderId,warehouseId);
        list.forEach(info->{
            info.setWarehouseId(warehouseId);
        });
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询订单中物料信息new", notes = "查询-订单sku(new)")
    @GetMapping("/getFinishDetailBy/{orderId}")
    public List<OrderSkuDetailSearchVo> getFinishDetailBy(@PathVariable("orderId")Long orderId) {
        return finishedOrderDetailService.listByInfoBy(orderId);
    }


}
